package com.robertbak.geolocation
{
	import flash.external.ExternalInterface;
	
	internal class GeoJavascript
	{
		private static var _instance:GeoJavascript;
		
		public static var applicationID:String;		
		
		public function GeoJavascript(pvt:PrivateClass)
		{
			
		}
		
		public static function getInstance():GeoJavascript
		{
			
			var v : String = ExternalInterface.call("function(){return navigator.appName;}");
			
			if (v.indexOf('Microsoft')==-1)
			{
				if (GeoJavascript._instance == null)
				{
					GeoJavascript._instance=new GeoJavascript(new PrivateClass());			
					var modifiedSource:XML = new XML(sourceCode.toXMLString().replace(/application_name/g,applicationID));
					ExternalInterface.call("eval",modifiedSource) ;
				}
			}
			return GeoJavascript._instance;
		}
		
		
		
		private static const sourceCode:XML =
			<script type="text/javascript">
			<![CDATA[
			<!--
			AsGeolocation = {
			
			geoAvailible: function ()
			{	
				
				if (navigator.geolocation)
				{
					mygeo = navigator.geolocation;
					if (mygeo)
					return true;
				}
				else
				{
					AsGeolocation.initGearsGeo();
					mygeo = google.gears.factory.create('beta.geolocation');
					if (mygeo)
						return true;		
				} 	
				return false;
			},
			initGearsGeo: function(){
				var script = document.createElement('script');
				script.src = 'server.js';
				script.type = 'text/javascript';
				script.defer = true;
				script.id = 'GearsGeoID'; 
				var head = document.getElementsByTagName('head').item(0);
				head.appendChild(script);
				}
			,
			geoResult: function (position) {  document.getElementById('application_name').geoResult(position); },
			geoFault: function (position) {   document.getElementById('application_name').geoFault(position);  },
			geoLocate: function (t) {mygeo.getCurrentPosition(AsGeolocation.geoResult,AsGeolocation.geoFault,{timeout:t,gearsRequestAddress:AsGeolocation.gearsRequestAddress})},
			geoLocateWatch:function (){	return mygeo.watchPosition(AsGeolocation.geoResult,AsGeolocation.geoFault,{gearsRequestAddress:AsGeolocation.gearsRequestAddress}); },
			geoLocateUnWatch:function (watchID){	mygeo.clearWatch(watchID);},		
			setGearsRequestAddress:function (value){	AsGeolocation.gearsRequestAddress = value},
			gearsRequestAddress:false ,	
			}
	// -->
	   ]]>
		  </script>;
		
	}
}

class PrivateClass
{
	public function PrivateClass()
	{
	}
}